using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;

namespace ibba.src.noriskbo
{
    public partial class App : Application
    {

        #region Variaveis Privadas

        private static System.Windows.Threading.DispatcherTimer _dispatcherTimer;
        private bool _atualizarPagina = true;
        private PageSistemaEmProcessamento _pageSistemaEmProcessamento;

        #endregion

        public static string XMLServidores { get; private set; }

        public App()
        {
            InitializeComponent();

            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");            
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("pt-BR");
            Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";

            this.Startup += this.Application_Startup;
            this.Exit += new EventHandler(App_Exit);
            this.UnhandledException += this.Application_UnhandledException;
            
            _dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            _dispatcherTimer.Interval = TimeSpan.FromSeconds(30);
            _dispatcherTimer.Tick += new EventHandler(_dispatcherTimer_Tick);
        }

        public static MainPageLM MainPage
        {
            get { return (MainPageLM)(App.Current.RootVisual as Grid).Children[0]; }
        }

        void _dispatcherTimer_Tick(object sender, EventArgs e)
        {
            _dispatcherTimer.Stop();

            if (_pageSistemaEmProcessamento == null)
                _pageSistemaEmProcessamento = new PageSistemaEmProcessamento();

            this.VerificarProcessamentoRisco();
        }

        void App_Exit(object sender, EventArgs e)
        {
            var svc = ServiceFactory.Instance.ServiceEnquadramentoDuplex;
            svc.BeginRemoverObservador(ServiceFactory.Instance.IdOberver, null, svc);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            XMLServidores = e.InitParams["XML_Servidores"];

            AppHelper.Servidor = this.Host.Source.DnsSafeHost; //e.InitParams["WebServer"];
            AppHelper.Servidor = AppHelper.Servidor.Trim();

            AppHelper.IdSistema = int.Parse(e.InitParams["IdSistema"]);
            AppHelper.NomeSistema = "NORISKBO";

            AppHelper.LoginUsuario = System.IO.Path.GetFileName(e.InitParams["UserName"]);
            AppHelper.NomeUsuario = System.IO.Path.GetFileName(e.InitParams["FullName"]);
            AppHelper.MaquinaUsuario = e.InitParams["UserHostName"].Split('.')[0];

            this.RootVisual = new Grid();            
            LogOut();
        }

        public static void LogOut()
        {
            _dispatcherTimer.Stop();

            var rootVisual = Application.Current.RootVisual as Grid;

            rootVisual.Children.Clear();
            rootVisual.Children.Add(new AppStartup());
        }

        public static void LogIn()
        {
            _dispatcherTimer.Start();

            var rootVisual = Application.Current.RootVisual as Grid;

            rootVisual.Children.Clear();
            rootVisual.Children.Add(new MainPageLM());
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            //Erro pe = new Erro(e.ExceptionObject.Message);
            //pe.Show();

            MessageBoxHelper.ShowErro(AppHelper.NomeSistema, "Erro inesperado!"
                                    , String.Format("{1}{0}{0}{2}", Environment.NewLine, e.ExceptionObject.Message, e.ExceptionObject.StackTrace));
        }

        private void VerificarProcessamentoRisco()
        {
            ServiceFactory.Instance.ServiceProcessamento.BeginObterProcessamento(DateTime.Now, VerificarProcessamentoRiscoCallBack,
                                                                                    ServiceFactory.Instance.ServiceProcessamento);
        }
        private void VerificarProcessamentoRiscoCallBack(IAsyncResult pAsyncResult)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                _dispatcherTimer.Start();
                try
                {
                    ServiceProcessamento.Processamento processamento = ((ServiceProcessamento.IServiceProcessamento)pAsyncResult.AsyncState).EndObterProcessamento(pAsyncResult);
                    if (processamento == null || processamento.Terminio.HasValue == false)
                    {
                        if (processamento == null)
                            _pageSistemaEmProcessamento.Show();
                        else
                            _pageSistemaEmProcessamento.Show(processamento.DataReferencia);

                        _atualizarPagina = true;
                    }
                    else
                    {
                        if (processamento.Terminio.HasValue)
                        {
                            if (_atualizarPagina)
                            {
                                _pageSistemaEmProcessamento.Close();
                                _atualizarPagina = false;
                            }
                        }                    
                    }

                }
                catch (Exception ex)
                {
                    _dispatcherTimer.Stop();
                    MessageBoxHelper.ShowErroMethod(AppHelper.NomeSistema, "VerificarProcessamentoRiscoCallBack", ex);
                }
            });
        }

        public static bool IsDesignTime
        {
            get
            {
                return (Application.Current == null) || (Application.Current.GetType() == typeof(Application));
            }
        }

        public static string FormatCPFouCNPJ(string pCnpjCpf)
        {
            try
            {
                if (pCnpjCpf.Trim().Length == 11)
                    return FormatCPFouCNPJ('F', pCnpjCpf);
                else
                    return FormatCPFouCNPJ('J', pCnpjCpf);
            }
            catch (Exception)
            {
                return pCnpjCpf;
            }

        }

        public static string FormatCPFouCNPJ(char pTipoPessoa, string pCnpjCpf)
        {
            try
            {
                if (pTipoPessoa.ToString().Equals("F", StringComparison.CurrentCultureIgnoreCase))
                    return Convert.ToDouble(pCnpjCpf.Trim()).ToString(@"000\.000\.000\-00");
                else
                    return Convert.ToDouble(pCnpjCpf.Trim()).ToString(@"000\.000\.000\/0000\-00");

            }
            catch (Exception)
            {
                return pCnpjCpf;
            }

        }
    }
}
